<template>
  <div class="min-h-screen bg-gradient-to-b from-gray-50 to-white">
    <main>
      <!-- 页面标题和搜索栏 -->
      <div class="mb-8">
        <div class="flex flex-col sm:flex-row items-center justify-between gap-6">
         
          <!-- 分类导航 -->
          <div class="flex-grow flex flex-wrap gap-0">
            <div v-for="category in categories" :key="category" :class="['cursor-pointer relative py-2 text-base font-medium transition-colors hover:bg-gray-50 px-4 rounded-md',
              selectedCategory === category ? 'text-blue-600 bg-blue-50' : 'text-gray-600 hover:text-blue-600']" 
              @click="handleCategorySelect(category)">
              {{ category }}
              <div
                class="absolute bottom-0 left-0 w-full h-0.5 bg-blue-600 transform origin-left transition-transform duration-300"
                :class="selectedCategory === category ? 'scale-x-100' : 'scale-x-0'" />
            </div>
          </div>
          <!-- 搜索栏 -->
          <div class="relative w-full sm:w-80">
            <a-input-search v-model:value="searchQuery" placeholder="搜索AI应用" class="w-full"
              :style="{ borderRadius: '9999px' }" />
          </div>
        </div>
      </div>

      <!-- 工具列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div v-for="tool in filteredTools" :key="tool.id"
          class="bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow duration-300 overflow-hidden border border-gray-100">
          <div class="p-6">
            <div class="flex items-center space-x-4 mb-4">
              <div class="w-12 h-12 rounded-lg overflow-hidden bg-gray-100">
                <img :src="tool.icon" :alt="tool.name" class="w-full h-full object-cover">
              </div>
              <div class="flex-grow">
                <h3 class="text-left text-base font-semibold text-gray-900">{{ tool.name }}</h3>
                <div class="flex items-center space-x-2 mt-1">
                  <span v-for="tag in tool.tags" :key="tag"
                    class="px-2 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-600">
                    {{ tag }}
                  </span>
                </div>
              </div>
            </div>
            <p class="text-sm text-gray-600 mb-4 line-clamp-2">{{ tool.description }}</p>
            <div class="flex items-center justify-between">
              <div class="flex items-center space-x-2">
                <div class="w-6 h-6 rounded-full ring-1 ring-blue-100 overflow-hidden">
                  <img :src="tool.author.avatar" :alt="tool.author.name" class="w-full h-full object-cover">
                </div>
                <span class="text-xs text-gray-700">{{ tool.author.name }}</span>
              </div>
              <a-button type="primary"
                class="!rounded-full !shadow-sm hover:!shadow-md !bg-gradient-to-r !from-blue-500 !to-blue-600 !border-0 !px-4 !text-xs !h-7"
                @click="handleViewDetails(tool)">
                查看详情
              </a-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="mt-6 flex justify-center">
        <a-pagination v-model:current="currentPage" :total="total" :pageSize="9" @change="handlePageChange" />
      </div>
    </main>
  </div>

  <!-- 发布工具弹窗 -->
  <PublishTool v-model:visible="showPublishModal" @submit="handlePublishTool" />
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { SearchOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { getRandomAvatar, getRandomTitle } from '@/utils/getRandomAvatar';
import { getToolsList } from '@/utils/api';
import PublishTool from '@/components/PublishTool.vue'
import $loading from '@/utils/loading';

const showPublishModal = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const selectedCategory = ref('')
const total = ref(0)

const categories = ['全部工具', 'AI Agent', '代码分析', '缺陷预测', 'AI工具']

const tools = ref([])

// 获取工具列表数据
const fetchToolsList = async () => {
  const loadingInstance = $loading.show();
  try {
    const res = await getToolsList({
      pageNum: currentPage.value,
      pageSize: 9,
      category: 'AI应用',
    })
    if (res) {
      tools.value = res.records.map(tool => ({
        id: tool.toolId,
        name: tool.toolName,
        icon: getRandomTitle(),
        url: tool.linkAddress,
        description: tool.functionDescription,
        tags: tool.tags ? tool.tags.split(',') : [],
        author: {
          name: tool.creators,
          avatar: getRandomAvatar()
        }
      }))
      total.value = res.total
    }
  } catch (error) {
    console.error('获取工具列表失败:', error)
  }finally {
    loadingInstance.close();
  }
}

const handlePublishTool = async (formData: any) => {
  tools.value.push({
    id: tools.value.length + 1,
    name: formData.name,
    icon: getRandomTitle(),
    url: formData.url,
    description: formData.description,
    tags: formData.tags,
    author: {
      name: '当前用户',
      avatar: getRandomAvatar()
    }
  })
  await fetchToolsList()
}

// 监听搜索和分类变化
watch([searchQuery, selectedCategory], () => {
  currentPage.value = 1
  fetchToolsList()
})

// 初始加载
fetchToolsList()


const filteredTools = computed(() => {
  return tools.value.filter(tool => {
    const matchesSearch = tool.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      tool.description.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesCategory = !selectedCategory.value || selectedCategory.value === '全部工具' ||
      tool.tags.some(tag => tag.includes(selectedCategory.value))
    return matchesSearch && matchesCategory
  })
})

const handleCategorySelect = (category: string) => {
  selectedCategory.value = category
}

const handlePageChange = async (page: number) => {
  currentPage.value = page
  await fetchToolsList()
}

const handleViewDetails = (tool: any) => {
  if (tool.url) {
    window.open(tool.url, '_blank')
  }
}
</script>